<template>
  <div>
    <el-upload :action="$http.adornUrl('alioss/upload')" :data="dataObj" list-type="picture-card" :file-list="fileList"
      :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview" :limit="maxCount"
      :on-exceed="handleExceed">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
  import { policy } from "./policy";
  import { getUUID } from '@/utils'
  export default {
    name: "multiUpload",
    props: {
      //图片属性数组
      value: [String, Object, Array],
      //最大上传图片数量
      maxCount: {
        type: Number,
        default: 30
      }
    },
    data() {
      return {
        dataObj: {
          policy: "",
          signature: "",
          key: "",
          ossaccessKeyId: "",
          dir: "",
          host: "",
          uuid: ""
        },
        fileList: [],
        dialogVisible: false,
        dialogImageUrl: null
      };
    },

    watch: {
      value: {
        async handler(val) {
          if (val) {
            // 首先将值转为数组
            let list;
            if (Array.isArray(val)) {
              list = val;
            } else {
              list = val.split(";");
            }
            // 然后将数组转为对象数组
            this.fileList = list.map((item, index) => {
              // 此处name使用ossId 防止删除出现重名
              item = { name: index, url: item };
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    },

    computed: {
      // fileList() {
      //   let fileList = [];
      //   for (let i = 0; i < this.value.length; i++) {
      //     fileList.push({ url: this.value[i] });
      //   }

      //   return fileList;
      // }
    },
    mounted() { },
    methods: {
      emitInput(fileList) {
        let value = [];
        for (let i = 0; i < fileList.length; i++) {
          value.push(fileList[i].url);
        }
        this.$emit("input", value);
      },
      handleRemove(file, fileList) {
        this.emitInput(fileList);
      },
      handlePreview(file) {

        this.dialogVisible = true;

        this.dialogImageUrl = file.url;
      },

      handleUploadSuccess(res, file) {
        this.fileList.push({
          url: res.data
        });
        this.emitInput(this.fileList);
      },
      handleExceed(files, fileList) {
        this.$message({
          message: "最多只能上传" + this.maxCount + "张图片",
          type: "warning",
          duration: 1000
        });
      }
    }
  };
</script>
<style>
</style>